package com.moodbox.server.mood.service.impl;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.moodbox.server.ai.service.AiAnalysisService;
import com.moodbox.server.mood.entity.Mood;
import com.moodbox.server.mood.mapper.MoodMapper;
import com.moodbox.server.mood.service.MoodService;
import com.moodbox.server.mood.service.UploadService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;

@Slf4j
@Service
@RequiredArgsConstructor
public class MoodServiceImpl extends ServiceImpl<MoodMapper, Mood> implements MoodService {

    private final UploadService uploadService;
    private final AiAnalysisService aiAnalysisService;

    @Override
    @Transactional
    public Mood createMood(
        String userId, 
        String textContent, 
        MultipartFile image, 
        MultipartFile audio,
        String emotionTag,
        Integer emotionIntensity
    ) {
        // 检查今日是否已经记录过心情
        Mood existingMood = getTodayMood(userId);
        if (existingMood != null) {
            throw new RuntimeException("今日已记录心情，不可重复记录");
        }

        // 上传文件
        String imageUrl = image != null ? uploadService.uploadImage(image) : null;
        String audioUrl = audio != null ? uploadService.uploadAudio(audio) : null;

        // AI分析心情
        AiAnalysisService.MoodAnalysisResult aiAnalysis = aiAnalysisService.analyzeMood(
            textContent, image, audio
        );

        // 如果没有传入情绪标签，使用AI分析结果
        if (emotionTag == null || emotionTag.isEmpty()) {
            emotionTag = aiAnalysis.emotionTag;
        }
        if (emotionIntensity == null) {
            emotionIntensity = (int) Math.round(aiAnalysis.emotionConfidence * 10);
        }

        // 创建心情记录
        Mood mood = new Mood()
            .setUserId(userId)
            .setTextContent(textContent)
            .setImageUrl(imageUrl)
            .setAudioUrl(audioUrl)
            .setEmotionTag(emotionTag)
            .setEmotionIntensity(emotionIntensity)
            .setAiAnalysis(aiAnalysis.emotionDescription)
            .setDeleted(0);

        // 保存心情记录
        this.save(mood);

        // 生成趣味报告
        String funReport = aiAnalysisService.generateFunReport(mood);
        mood.setAiAnalysis(funReport);
        this.updateById(mood);

        return mood;
    }

    @Override
    public Mood getTodayMood(String userId) {
        // 获取今天的开始和结束时间
        LocalDateTime startOfDay = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);
        LocalDateTime endOfDay = LocalDateTime.of(LocalDate.now(), LocalTime.MAX);

        // 查询今日心情
        return this.getOne(
            new LambdaQueryWrapper<Mood>()
                .eq(Mood::getUserId, userId)
                .between(Mood::getCreateTime, startOfDay, endOfDay)
        );
    }

    @Override
    public Page<Mood> getMoodHistory(String userId, Page<Mood> page) {
        return this.page(
            page, 
            new LambdaQueryWrapper<Mood>()
                .eq(Mood::getUserId, userId)
                .orderByDesc(Mood::getCreateTime)
        );
    }

    @Override
    @Transactional
    public boolean deleteMood(String userId, String moodId) {
        // 检查心情记录是否属于该用户
        Mood mood = this.getById(moodId);
        if (mood == null || !mood.getUserId().equals(userId)) {
            return false;
        }

        // 删除心情记录
        return this.removeById(moodId);
    }

    @Override
    public String getWeekReport(String userId) {
        return aiAnalysisService.generateWeekReport(userId);
    }
} 